import xml2js from "xml2js";
import crypto from "crypto";

export default {
  aes256Decrypt(data, key) {
    const cipher = crypto.createDecipheriv("aes-256-ecb", key, "");
    let c = cipher.update(data, "base64", "utf8");
    c += cipher.final("utf8");
    return c;
  },
  sortedQueryString(query, opts = {}) {
    const { excludeKeys = [], encode } = opts;
    return Object.keys(query)
      .filter(function (key) {
        const val = query[key];
        return (
          val !== undefined && val !== "" && excludeKeys.indexOf(key) == -1
        );
      })
      .sort()
      .map(function (key) {
        let val = query[key];
        if (encode) val = encodeURIComponent(val);
        return key + "=" + val;
      })
      .join("&");
  },
  sha256(msg, key) {
    const hmac = crypto.createHmac("sha256", key);
    return hmac.update(msg).digest("hex");
  },
  sign: function (object, key) {
    var str = this.sortedQueryString(object);
    if (key) str += "&key=" + key;

    return this.sha256(str, key).toUpperCase();
  },
  getTimestamp: function () {
    return parseInt(Date.now() / 1000) + "";
  },

  genNonceStr(len = 24, radix = 36) {
    let str = "";
    while (str.length < len) {
      str += Math.random().toString(radix).substr(2);
    }
    return str.substr(0, len);
  },

  buildXML: function (json) {
    var builder = new xml2js.Builder();
    return builder.buildObject({
      xml: json,
    });
  },
  parseXML: function (xml) {
    var parser = new xml2js.Parser({
      trim: true,
      explicitArray: false,
      explicitRoot: false,
    });
    return new Promise((resolve, reject) => {
      parser.parseString(xml, (err, result) => {
        if (err) reject(err);
        else resolve(result);
      });
    });
  },
};
